package com.zlcx.tz.live.processor.impl;

import com.netflix.hystrix.exception.HystrixRuntimeException;
import com.zlcx.tz.live.client.UserClient;
import com.zlcx.tz.live.constant.LearningStatus;
import com.zlcx.tz.live.processor.SitUpPostProcessor;
import com.zlcx.tz.live.vo.LearnTimeParamVO;
import com.zlcx.tz.live.vo.ResultVO;
import com.zlcx.tz.live.vo.TimeLearnRoomSeatsDTO;
import com.zlcx.tz.live.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

import static com.zlcx.tz.live.vo.LearnTimeParamVO.TypeEnums.TIME_LEARN_ROOM_END;

/**
 * @author: anjl
 * @description: （同步）记录学习记录
 * @data: 2020-09-27
 **/
@Slf4j
@Order(10)
@Component
public class EndTimingPostProcessor implements SitUpPostProcessor<TimeLearnRoomSeatsDTO> {

    @Override
    public void processor(TimeLearnRoomSeatsDTO seat) {

        Asserts.notNull(seat, "seat is null !");
        log.info("计时房间操作-结束-记录学习计时操作 seat = {}", seat);
        LearnTimeParamVO learnTimeParams = buildParams(seat);

        try {
            ResultVO result = userClient.addUserLearnTime(learnTimeParams);
            log.info("计时房间操作-用户结束学习计时结果 seat = {} result = {}", seat, result);
        } catch (HystrixRuntimeException e) {
            UserVO user = userClient.findOne(seat.getUserId()).getData();
            if (Objects.nonNull(user) && LearningStatus.NO_TIMING.getCode() == user.getStatus()) {
                log.info("计时房间操作-用户没有学习，直接结束计时自习室计时 seat = {}", seat);
            } else {
                throw e;
            }
        }

    }

    private LearnTimeParamVO buildParams(TimeLearnRoomSeatsDTO seat) {
        Date now = new Date();
        return LearnTimeParamVO.builder()
                .userId(seat.getUserId())
                .roomId(seat.getRoomId())
                .startTime(DateFormatUtils.format(seat.getSeatingTime(), "yyyy-MM-dd HH:mm:ss"))
                .endTime(DateFormatUtils.format(now, "yyyy-MM-dd HH:mm:ss"))
                .lianMaiId(seat.getId())
                .studyMinuteSeconds((now.getTime() - seat.getSeatingTime().getTime()) / 1000)
                .studyInfoName(seat.getStudyContent())
                .type(TIME_LEARN_ROOM_END.code)
                .build();
    }

    @Autowired
    private UserClient userClient;

}
